<!--登录导航页-->
<template>
  <div class="topTool">
    <div class="login-ygc">
      <div class="logo-ygc">
        <img src="../assets/out_resource/images/logo.png" width="45px" height="50px">
        <span style="color: #FFFFFF; font-weight: 600; margin-left: 5px;">{{$store.state.global.title}} | </span>
        <span style="color: #FFFFFF; font-size: 8px">登录入口</span>
      </div>
      <div class="regLog">
        <el-form ref="user" :model="user" :rules="rules"  v-show="false" >
           <el-form-item label="" prop="userName">
          <el-input   @keyup.enter.native="login" placeholder="用户名" v-model="user.userName" style="margin-bottom: 10px;"></el-input>
           </el-form-item>
            <el-form-item label="" prop="password">
          <el-input   @keyup.enter.native="login" placeholder="密码" v-model="user.password" type="password" style="margin-bottom: 10px;"></el-input>
          </el-form-item>
        </el-form>
        <div class="remember" v-show="false">
          <el-checkbox  v-model="recordPsw" style="float: left;"><span style="color: #FFFFFF; font-size: 10px;">记住密码</span></el-checkbox>
          <a href="#" style="color: #3A6BFF; font-size: 10px; float: right">忘记密码</a>
        </div>
        <el-button
          size="medium"
          type="primary"
          style="width:260px; background-color: #003DF4; margin-top: 20px; border-radius: 30px;margin-bottom:20px"
          @click="login"
        >
          <span>登 录</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserInfo } from "../api/sourceDetail";
import { roleMenuTreeselect } from "@/api/baseSetting";

require("../assets/out_resource/js/jquery-1.4.2.min");
require("../assets/out_resource/js/jquery.SuperSlide");
import { mapGetters } from "vuex";
import { login } from "@/api/sourceDetail";
const isDev = process.env.NODE_ENV !== "production";
export default {
  name: "LoginBanner",
  data: function() {
    return {
      recordPsw: false,
      user: {
        userName: "",
        password: ""
      },
      loading1: false,
      clientId: "2f59ad62-e916-4411-87cc-e58223205445",
      clientSecret: "9O_i2eE3Q9yq9C-eKqsVyA",
      rules: {
        // userName: [
        //   { required: true, message: "请输入用户名！", trigger: "blur" }
        //   // {
        //   //   min: 3,
        //   //   max: 16,
        //   //   message: "用户名长度有误，请检查！",
        //   //   trigger: "blur"
        //   // }
        // ],
        // password: [
        //   { required: true, message: "请输入密码！", trigger: "blur" }
        //   // {
        //   //   min: 4,
        //   //   max: 22,
        //   //   message: "密码长度有误，请检查！",
        //   //   trigger: "blur"
        //   // }
        // ]
      },
      checkedKeysList: [],
      menusAll: []
    };
  },
  computed: {
    ...mapGetters(["httpServer", "httpClient", "httpOauth", "title"])
  },
  created() {
    if ("Chrome" != this.myBrowser()) {
      alert("推荐使用Chrome内核浏览器!");
    }
    //单点登录
    this.onload();
    // if(isDev) {
    this.applyAccessToken();
    //  this.checkToken();
    // }
  },
  mounted() {
    this.$("body").addClass("loaded");
    this.$("#loader-wrapper .load_title").remove();
  },
  methods: {
    applyAccessToken() {
      if (!localStorage.getItem("accessToken")) {
        //判断本地accessToken是否存在，不存在
        var code = this.getParameter("code"); //从网址栏获取返回的code

        if (code != null) {
          //地址栏存在code，进入
          var url = this.httpOauth + "/accessToken";
          var httpClient = this.$store.state.global.httpClient;
          var that = this;
          this.$.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            data: {
              grant_type: "authorization_code",
              client_id: that.clientId,
              client_secret: that.clientSecret,
              code: code,
              redirect_uri: httpClient
            },
            success: function(data) {
              //                data = JSON.parse(data.replace(/&quot;/g,"\""));
              localStorage.setItem("accessToken", data.access_token);
              location.href = httpClient + "/home/main";
            }
          });
        }
      } else {
        //本地accessToken已存在,校验时效性
        this.checkToken(); //校验token时效性，失效则重新授权
      }
    },
    //单点登录信息
    onload() {
      var sessionId = this.getParameter("TIPDM_SESSIONID");
      if (sessionId) {
        localStorage.setItem("accessToken", sessionId);
        this.checkToken();
      }
      var loggedOut = this.getParameter("logged_out");
      if (loggedOut) {
        localStorage.removeItem("accessToken");
      }
    },
    getParameter(name) {
      var url = window.location.href;
      var reg = new RegExp(name + "=([^&]*)(?:&)?");
      return url.match(reg) && url.match(reg)[1];
    },

    //获取已授权的权限
    getCheckedAuth(roleId) {
      return roleMenuTreeselect(roleId, 1).then(response => {
        // if(response.code === 200 && response.menus && response.menus.length){
        //   let newArr = response.menus.slice(response.menus.length - 5,response.menus.length)
        //   // console.log(newArr);
        //   // this.menuOptions = response.menus;
        //   this.menuOptions = newArr
        //   return response;
        // }

        if (response.code === 200) {
          return response;
          // this.menusAll = response.menus
          // this.checkedKeysList = this.checkedKeysList.concat(response.checkedKeys)
          // this.checkedKeysList = [...new Set(this.checkedKeysList)]
        }
      });
    },

    login() {
      // this.$refs["user"].validate(valid => {
      // if (valid) {
      this.$store.dispatch("login", this.user).then(e => {
        const loading = this.$loading({
          lock: true,
          text: "跳转中，请稍后 ...",
          background: "rgba(255,255,255,0.8)"
        });

        getUserInfo().then(res => {
          // console.log(res);
          if (res.status === "SUCCESS") {
            localStorage.setItem("userAuthList", (res.data || []).toString());
            let authObj = {};

            let isAdminTimes = 0;
            res.data &&
              res.data.forEach(val => {
                if (val.indexOf("admin") >= 0) {
                  // authObj['isAdmin'] = true
                  isAdminTimes += 1;
                }
              });
            // console.log(isAdminTimes);
            if (isAdminTimes > 0) {
              localStorage.setItem("isAdminAuth", "1");
            } else {
              localStorage.setItem("isAdminAuth", "0");
            }

            let ids = [];
            res.roles &&
              res.roles.forEach(ele => {
                ids.push(this.getCheckedAuth(ele.roleId));
              });

            Promise.all(ids).then(result => {
              // console.log(result);
              result &&
                result.forEach(ele => {
                  this.menusAll = ele.menus.slice(
                    ele.menus.length - 5,
                    ele.menus.length
                  );
                  this.checkedKeysList = this.checkedKeysList.concat(
                    ele.checkedKeys
                  );
                  this.checkedKeysList = [...new Set(this.checkedKeysList)];
                });

              this.$nextTick(() => {
                let authObj = [];
                // console.log(this.menusAll);
                // console.log(this.checkedKeysList);
                this.checkedKeysList &&
                  this.checkedKeysList.forEach(item => {
                    this.menusAll &&
                      this.menusAll.forEach(val => {
                        if (item.toString() === val.id.toString()) {
                          authObj.push(val);
                        }
                      });
                  });
                let authNameStr = [];
                authObj.forEach(e => {
                  authNameStr.push(e.label);
                });
                // console.log(authObj);
                localStorage.setItem("authObj", JSON.stringify(authObj));
                localStorage.setItem("authNameStr", authNameStr.toString());

                // console.log(res.data);
                if (res.data && res.data.indexOf("admin") >= 0) {
                  //admin 账户
                  // console.log(111);
                  let newAuthObj = [];
                  let newAuthNameStr = [];
                  this.menusAll &&
                    this.menusAll.forEach(val => {
                      newAuthObj.push(val);
                      newAuthNameStr.push(val.label);
                    });
                  localStorage.setItem("isAdminAuth", "1");
                  localStorage.setItem("authObj", JSON.stringify(newAuthObj));
                  localStorage.setItem(
                    "authNameStr",
                    newAuthNameStr.toString()
                  );
                }

                this.$router.push("/home");
              });
            });
          } else {
            this.$message.error("获取用户权限失败！");
          }
        });

        loading.close();
      });
      // }
      // });

      // if (isDev) {
      // location.href =
      //   this.httpOauth +
      //   "/authorize?client_id=" +
      //   this.clientId +
      //   "&response_type=code&redirect_uri=" +
      //   this.$store.state.global.httpClient +
      //   "/login_banner";
      // } else if (!isDev) {
      //   location.href = this.httpClient + "/authorize";
      // }
    },
    //登录，重新获取授权
    myBrowser() {
      var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
      var isOpera = userAgent.indexOf("Opera") > -1;
      if (isOpera) {
        return "Opera";
      } //判断是否Opera浏览器
      if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
      } //判断是否Firefox浏览器
      if (userAgent.indexOf("Chrome") > -1) {
        return "Chrome";
      }
      if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
      } //判断是否Safari浏览器
      if (
        userAgent.indexOf("compatible") > -1 &&
        userAgent.indexOf("MSIE") > -1 &&
        !isOpera
      ) {
        return "IE";
      } //判断是否IE浏览器
    },
    checkToken() {
      var that = this;
      $.ajax({
        url: that.httpServer + "/token/check",
        method: "get",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        beforeSend: function(xhr) {
          xhr.setRequestHeader("accessToken", localStorage.accessToken);
        },
        success: function(data) {
          if (data == null) {
            localStorage.removeItem("accessToken");
            that.$store.commit("dealRequestError", {
              status: 401,
              responseJSON: {
                message: "服务器无法连接，请联系管理员！"
              }
            });
          } else {
            if (data.status == "SUCCESS") {
              location.href = "/home/main";
            } else if (data.status == "FAIL") {
              localStorage.removeItem("accessToken");
              console.log("token 失效");
            }
          }
        },
        error: function(error) {
          console.error(error);
        }
      });
    }
  }
};
</script>
<style>
@import "../assets/out_resource/css/guide.css";
.el-form-item__error {
  margin-left: 50px;
}
</style>
